<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="addRules">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!--  表格区域  -->
    <div class="table">
      <el-table
        :data="ruleList"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column
          prop="ruleNumber"
          label="计费规则编号"
        />
        <el-table-column
          prop="ruleName"
          label="计费规则名称"
        />
        <el-table-column
          prop="freeDuration"
          label="免费时长(分钟)"
        />
        <el-table-column
          prop="chargeCeiling"
          label="收费上线(元)"
        />
        <el-table-column
          label="计费方式"
        >
          <template #default="scope">
            {{ formatChargeType(scope.row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="计费规则"
          prop="ruleNameView"
        />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" @click="showRule(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="deleteRule(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--  分页  -->
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        background
        :total="total"
        :page-size="params.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>

    <div class="dialog">
      <el-dialog
        :title="row_id===null?'增加停车计费规则':'编辑停车计费规则'"
        :visible.sync="dialogVisible"
        width="580px"
        :before-close="dialogCloseHandle"
      >
        <div class="form-container">
          <el-form ref="carForm" :model="carForm" :rules="carFormRules" label-position="top">
            <el-form-item label="计费规则编号" prop="ruleNumber">
              <el-input v-model="carForm.ruleNumber" placeholder="请输入计费规则编号" />
            </el-form-item>
            <el-form-item label="计费规则名称" prop="ruleName">
              <el-input v-model="carForm.ruleName" placeholder="请输入计费规则名称" />
            </el-form-item>
            <el-form-item label="计费方式（全天收费）" prop="chargeType">
              <el-radio-group v-model="carForm.chargeType">
                <el-radio label="duration">时长收费</el-radio>
                <el-radio label="turn">按次收费</el-radio>
                <el-radio label="partition">分段收费</el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="flex-container">
              <el-form-item label="免费时长" prop="freeDuration">
                <el-input v-model="carForm.freeDuration" placeholder="请输入免费时长" />分钟
              </el-form-item>
              <el-form-item label="收费上限" prop="chargeCeiling">
                <el-input v-model="carForm.chargeCeiling" placeholder="请输入收费上限" />元
              </el-form-item>
            </div>
            <el-form-item label="计费规则">
              <!--    按时长收费区域          -->
              <div v-if="carForm.chargeType==='duration'" class="duration">
                每<el-input v-model="carForm.durationTime" class="input-box" /> 小时
                <el-input v-model="carForm.durationPrice" class="input-box" /> 元
              </div>
              <!--    按次收费区域          -->
              <div v-if="carForm.chargeType==='turn'" class="turn">
                每次<el-input v-model="carForm.turnPrice" class="input-box" />元
              </div>
              <!--    分段收费区域          -->
              <div v-if="carForm.chargeType==='partition'" class="partition">
                <div class="item">
                  <el-input v-model="carForm.partitionFrameTime" class="input-box" />小时内,每小时收费
                  <el-input v-model="carForm.partitionFramePrice" class="input-box" /> 元
                </div>
                <div class="item">
                  每增加<el-input v-model="carForm.partitionIncreaseTime" class="input-box" />小时,增加
                  <el-input v-model="carForm.partitionIncreasePrice" class="input-box" /> 元
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <el-button @click="dialogCloseHandle">取 消</el-button>
          <el-button type="primary" @click="confirmAdd">确 定</el-button>
        </template>
      </el-dialog>

    </div>
  </div></template>
<script>
import { getRuleListAPI } from '@/api/car'
import { createRuleAPI, deleteRuleAPI, showRuleAPI, editRuleAPI } from '@/api/rule'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'CarRule',
  data() {
    return {
      carForm: {
        ruleNumber: '', // 计费规则编号
        ruleName: '', // 计费规则名称
        freeDuration: null, // 免费时长，单位:分钟
        chargeCeiling: null, // 收费上限
        chargeType: 'duration', // 收费类型，时长收费:duration,按次收费:turn,分段收费: partition 枚举值: duration turn partition
        durationTime: null, // 时长计费单位时间
        durationPrice: null, // 时长计费单位价格
        durationType: 'hour', // 时长收费类型 minute:分钟，hour:小时 枚举值: minute hour
        turnPrice: null, // 按次收费：每次价格
        partitionFrameTime: null, // 分段收费:段内时间
        partitionFramePrice: null, // 分段收费:段内费用
        partitionIncreaseTime: null, // 分段收费:超出时间
        partitionIncreasePrice: null // 分段收费:超出范围收费价钱
      },
      carFormRules: {
        ruleNumber: [
          {
            required: true,
            message: '请输入规则编号',
            trigger: 'blur'
          }
        ],
        ruleName: [
          {
            required: true,
            message: '请输入规则名称',
            trigger: 'blur'
          }
        ],
        chargeType: [
          {
            required: true,
            message: '请选择收费类型',
            trigger: 'blur'
          }
        ]
      }, // 计费规则校验规则对象
      ruleList: [],
      params: {
        page: 1,
        pageSize: 3
      },
      total: 0,
      dialogVisible: false,
      row_id: null // 打开行号id
    }
  },
  mounted() {
    this.getRulesList()
  },
  methods: {
    // 查看计费规则
    async showRule(id) {
      const res = await showRuleAPI(id)
      this.carForm = res.data
      this.row_id = id
      this.dialogOpenHandle()
    },
    // 删除计费规则
    deleteRule(id) {
      this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteRuleAPI(id)
        if (res.code === 10000) {
          await this.getRulesList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } else {
          this.$message({
            type: 'error',
            message: '失败!' + res.msg
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async exportToExcel() {
      this.params.pageSize = 1000
      const res = await getRuleListAPI(this.params)
      this.params.pageSize = 3
      // debugger
      // 表头英文字段key
      const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView']
      // 表头中文字段value
      const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上线(元)', '计费方式', '计费规则']

      const sheetData = res.data.rows.map((item) => {
        const obj = {}
        tableHeaderKeys.forEach(key => {
          // 赋值
          // 针对计费规则做处理
          if (key === 'chargeType') {
            obj[key] = this.formatChargeType(item[key])
          } else {
            obj[key] = item[key]
          }
        })
        return obj
      })

      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 创建一个工作表 要求一个对象数组格式
      const worksheet = utils.json_to_sheet(sheetData)
      // 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      // 导出方法进行导出
      writeFileXLSX(workbook, '收费规则.xlsx')
    },
    exportToExcelDemo() {
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 创建一个工作表 要求一个对象数组格式
      const worksheet = utils.json_to_sheet(
        [
          { name: '张三', age: 18 },
          { name: '李四', age: 28 }
        ]
      )

      // 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [['姓名', '年龄']], { origin: 'A1' })
      // 导出方法进行导出
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },
    formatChargeType(type) {
      const TYPEMAP = {
        'duration': '按时长收费',
        'turn': '按次收费',
        'partition': '分段收费'
      }
      return TYPEMAP[type]
    },
    // 创建收费规则
    confirmAdd() {
      this.$refs.carForm.validate(async valid => {
        if (!valid) return
        if (this.row_id === null) {
          await createRuleAPI(this.carForm)
        } else {
          const res = await editRuleAPI(this.carForm)
          console.log(res)
          this.$message.success(res.msg)
        }
        await this.getRulesList()
        this.dialogCloseHandle()
      })
    },
    // 新增规则
    addRules() {
      this.carForm = {
        ruleNumber: '', // 计费规则编号
        ruleName: '', // 计费规则名称
        freeDuration: null, // 免费时长，单位:分钟
        chargeCeiling: null, // 收费上限
        chargeType: 'duration', // 收费类型，时长收费:duration,按次收费:turn,分段收费: partition 枚举值: duration turn partition
        durationTime: null, // 时长计费单位时间
        durationPrice: null, // 时长计费单位价格
        durationType: 'hour', // 时长收费类型 minute:分钟，hour:小时 枚举值: minute hour
        turnPrice: null, // 按次收费：每次价格
        partitionFrameTime: null, // 分段收费:段内时间
        partitionFramePrice: null, // 分段收费:段内费用
        partitionIncreaseTime: null, // 分段收费:超出时间
        partitionIncreasePrice: null // 分段收费:超出范围收费价钱
      }
      this.dialogOpenHandle()
    },
    // 打开弹窗
    dialogOpenHandle() {
      this.dialogVisible = true
    },
    // 关闭弹窗
    dialogCloseHandle() {
      this.row_id = null
      this.dialogVisible = false
    },
    // 页面变化时
    handleCurrentChange(page) {
      this.params.page = page
      this.getRulesList()
    },
    // 获取规则列表数据
    async getRulesList() {
      const res = await getRuleListAPI(this.params)
      this.ruleList = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>
<style lang="scss" scoped>
.rule-container{
  padding: 20px;
  background-color: #fff;
}
.search-container{
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;
  .search-label{
    width: 100%;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding: 4px 0px;
  text-align: right;
}
.form-container{
  padding: 0 80px;
}
.flex-container{
  display: flex;
}
.duration{
  display: flex;
}
.turn{
  display: flex;
}
.partition .item{
  display: flex;
}
</style>
